<template>
    <div class="address-selector">
        <h1>修改收货地址</h1>

        <div class="selector-group">
            <label>省份：</label>
            <select v-model="province" @change="ProvinceChange">
                <option value="">请选择省份</option>
                <option v-for="(province, code) in provinces" :key="code" :value="code">
                    {{ province.n }}
                </option>
            </select>
        </div>

        <div class="selector-group">
            <label>城市：</label>
            <select v-model="city" @change="CityChange" :disabled="!province">
                <option value="">请选择城市</option>
                <option v-for="(city, code) in cities" :key="code" :value="code">
                    {{ city.n }}
                </option>
            </select>
        </div>

        <div class="selector-group">
            <label>区县：</label>
            <select v-model="county" :disabled="!city">
                <option value="">请选择区县</option>
                <option v-for="(county, code) in counties" :key="code" :value="code">
                    {{ county.n }}
                </option>
            </select>
        </div>

        <div class="selector-group">
            <label>详细地址：</label>
            <textarea v-model="xiangxi" placeholder="请输入详细地址，如街道、楼牌号等"></textarea>
        </div>

        
             <div class="selector-group">
                <label>收件人</label>
                <textarea v-model="name" placeholder="收件人"></textarea>
            </div>

            <div class="selector-group">
                <label>联系电话</label>
                <textarea v-model="phone" placeholder="联系电话"></textarea>
            </div>


        <div class="selector-group">
            <label>备注</label>
            <textarea v-model="remark" placeholder="备注"></textarea>
        </div>

        <div class="form-actions">
            <button @click="saveUpdateAddress()">保存修改</button>
            <button @click="goBack()">返回</button>
        </div>

        <div class="selected-address" v-if="fullAddress">
            <h3>选中的地址：</h3>
            <p>{{ fullAddress }}</p>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Area from '/public/area_format_object.json'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()


const provinces = ref(Area)
const cities = ref({})
const counties = ref({})

const province = ref('')
const city = ref('')
const county = ref('')
const xiangxi = ref('')
const remark = ref('')
const name = ref('')
const phone = ref('')
const addressId = ref(null)


const goBack = () => {
    router.back()
}

const ProvinceChange = () => {
    city.value = ''
    county.value = ''
    if (province.value && Area[province.value]) {
        cities.value = Area[province.value].c || {}
    } else {
        cities.value = {}
    }
    counties.value = {}
}

const CityChange = () => {
    county.value = ''
    if (city.value && cities.value[city.value]) {
        counties.value = cities.value[city.value].c || {}
    } else {
        counties.value = {}
    }
}

const fullAddress = computed(() => {
    let address = ''
    if (province.value && Area[province.value]) {
        address += Area[province.value].n
    }
    if (city.value && Area[province.value] && Area[province.value].c[city.value]) {
        address += ' ' + Area[province.value].c[city.value].n
    }
    if (county.value && cities.value[city.value] && cities.value[city.value].c[county.value]) {
        address += ' ' + cities.value[city.value].c[county.value].n
    }
    if (xiangxi.value) {
        address += ' ' + xiangxi.value.trim()
    }
    return address
})

// 解析地址字符串
const parseAddress = (addressStr) => {
    if (!addressStr) return

    const addressParts = addressStr.split(' ')

    const provincePart = addressParts[0]
    const cityPart = addressParts[1]
    const countyPart = addressParts[2]
    const detailPart = addressParts.slice(3).join(' ')

    // 查找省份
    for (const code in Area) {
        const provinceName = Area[code].n
        if (provinceName === provincePart) {
            province.value = code
            // 更新市
            if (Area[code].c) {
                cities.value = Area[code].c
            }
            break
        }
    }

    // 查找市
    if (province.value && Area[province.value]?.c) {
        const citiesData = Area[province.value].c
        for (const code in citiesData) {
            const cityName = citiesData[code].n
            if (cityName === cityPart) {
                city.value = code
                // 更新区县
                if (citiesData[code].c) {
                    counties.value = citiesData[code].c
                }
                break
            }
        }
    }

    // 查找区县
    if (city.value && cities.value[city.value]?.c) {
        const countiesData = cities.value[city.value].c
        for (const code in countiesData) {
            const countyName = countiesData[code].n
            if (countyName === countyPart) {
                county.value = code
                break
            }
        }
    }

    xiangxi.value = detailPart
}

// 详情
const getAddressDetail = async (id) => {

    const response = await axios.get('/api/getUserAddressById', {
        params: { id: id }
    })

    if (response.data.code === 5200) {
        console.log("11", response.data);

        const addressData = response.data.userAddress
        addressId.value = addressData.id
        remark.value = addressData.remark
        name.value = addressData.name
        phone.value = addressData.phone


        parseAddress(addressData.address)
    } else {
        alert('获取地址信息失败')
    }

}

// 保存修改
const saveUpdateAddress = async () => {
    if (!province.value) {
        alert('请选择省份')
        return
    }

    if (!city.value) {
        alert('请选择城市')
        return
    }

    if (!county.value) {
        alert('请选择区县')
        return
    }

    if (!xiangxi.value.trim()) {
        alert('请输入详细地址')
        return
    }

    if (!name.value.trim()) {
        alert('收件人不能为空')
        return
    }

    if (!phone.value.trim()) {
        alert('收件人电话不能为空')
        return
    }

    const userId = window.sessionStorage.getItem('id')

    const updateData = {
        id: addressId.value,
        userId: userId,
        address: fullAddress.value,
        remark: remark.value,
        name: name.value,
        phone: phone.value
    }

    


    const response = await axios.post('/api/updateUserAddress', updateData, {
        headers: {
            'Content-Type': 'application/json'
        }
    })

    console.log('保存的地址数据:', updateData)
    if (response.data.code !== 5200) {
        alert('地址保存失败')
        return
    }
    alert('地址保存成功')
    router.back()

}


onMounted(() => {
    const id = route.query.id || route.params.id
    if (id) {
        getAddressDetail(id)
    } else {
        alert('未找到地址ID')
        router.push('/addressList')
    }
})
</script>

<style scoped>
.address-selector {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
}

.address-selector h1 {
    text-align: center;
    margin-bottom: 30px;
}

.form-group,
.selector-group {
    margin-bottom: 20px;
}

.form-group label,
.selector-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
}

.form-group input,
.form-group textarea,
.selector-group select,
.selector-group textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

.form-group textarea,
.selector-group textarea {
    height: 80px;
    resize: vertical;
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 30px;
}

.selected-address {
    margin-top: 30px;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #b8daff;
}
</style>